﻿using EnterpriseInformation.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EnterpriseInformation.Filters
{
    public class LoginActionFilter: IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ActionName == "Index" || ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ActionName == "test")
            {
                await next();
            }
            else
            {
                JObject jobj = new JObject();
                int loadcount = 0;

                while ((BackService.userHelperList == null ||
                     BackService.userHelperList.Count < 1) && loadcount < 2)
                {
                    BackService.loadUserInfo();
                    loadcount += 1;
                }

                if (BackService.userHelperList == null ||
                     BackService.userHelperList.Count < 1)
                {
                    jobj["status"] = -1;
                    jobj.Add(new JProperty("message", "1系统发生问题！"));
                    await context.HttpContext.Response.WriteAsync(jobj.ToString());
                }
                else
                {
                    BackService.checkUserStatus();
                    if (BackService.userHelperList != null &&
                     BackService.userHelperList.Count > 0)
                    {
                        await next();
                    }
                    else
                    {
                        jobj["status"] = -1;
                        jobj.Add(new JProperty("message", "2系统发生问题！"));
                        await context.HttpContext.Response.WriteAsync(jobj.ToString());
                    }
                }
            }
            
        }
    }
}
